package org.UserHouse.Servlet;

import com.google.gson.Gson;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import org.UserHouse.vo.ResponseData;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

/**
 * @author bin
 * @date 2024-12-17
 */
@WebServlet("/fileImg.do")
@MultipartConfig
public class uploadFileImgServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        Gson gson = new Gson();
//        Part part = req.getPart("file");
        Collection<Part> parts = req.getParts();

        PrintWriter out = resp.getWriter();


        ServletContext servletContext = req.getServletContext();
        String realPath = servletContext.getRealPath("/img/");

        File file = new File(realPath);
        if (file.exists()) {
            file.mkdir();
        }


        for (Part part : parts) {
            String filename = part.getSubmittedFileName();
            part.write(realPath + filename);
            ResponseData responseData = new ResponseData();
            responseData.setCode(0);
            responseData.setData(filename);

            String json = gson.toJson(responseData);
            out.println(json);
        }

        out.flush();
        out.close();
    }
}
